<?php
class Answer_Service_Level extends Phpfox_Service {
    function __construct()
    {
        $this->_sTable = Phpfox::getT('brodev_answer_level');
        $this->_sTableUser = Phpfox::getT('user');
        $this->_sTableParent = Phpfox::getT('user_group');
    }

    /**
     * get categories from database without page
     * @param string $sFields
     * @param array $aConditions
     * @return array
     */
    public function getListNoPage($sFields = 'l.*', $aConditions = array()) {
        $aCategories = $this->database()
            ->select($sFields .', g.title as group_name, pg.title as previous_group_name')
            ->from($this->_sTable, 'l')
            ->where($this->getCondition($aConditions))
            ->leftJoin($this->_sTableParent, 'g', 'l.group_id = g.user_group_id')
            ->leftJoin($this->_sTableParent, 'pg', 'l.previous_group = pg.user_group_id')
            ->order('l.minpoint')
            ->execute('getRows')
        ;
        return array(
            'data' => $aCategories
        );
    }

    /**
     * convert array to condition string
     * @param array $aCondition
     * @return string
     *
     */
    private function getCondition( $aCondition ) {
        $sCondition = "1=1";
        foreach ($aCondition AS $Array) {
            $sCondition .= " AND ". $Array;
        }
        return $sCondition;
    }

    /**
     * get 1 category from database with condition
     * @param array $aCondition
     * @return array
     */
    public function getForEdit( $aCondition ) {
        $aCategory = $this->database()
            ->select('*')
            ->from($this->_sTable)
            ->where( $this->getCondition($aCondition))
            ->execute('getRow');
        return array(
            'data'=>$aCategory
        );
    }

    /**
     * insert or update category to database
     * @param $aVals
     * @param $iId
     * @return bool
     */
    public  function saveDatabase($aVals) {
        $iId = $aVals['id'];
        $aCondition = array('id = '. (int) $iId);
        if ( !$this->isExist($aCondition) ) {
            $iId = $this->database()
                ->insert($this->_sTable, $aVals)
            ;
            if (!$iId)
            {
                return false;
            }
            else {
                return true;
            }
        }
        else {
            return $this->database()->update($this->_sTable, $aVals, "id = " . $iId);
        }
    }

    /**
     * delete category from database      *
     * @param $iId
     * @return bool
     */
    public function delete($iId) {
        return  $this->database()->delete($this->_sTable, 'id = ' . $iId);
    }
    /**
     * delete all level     *
     * @param $iId
     * @return bool
     */
    public function deleteAll() {
        return $this->database()->delete($this->_sTable,'1 = 1');
    }
    /**
     * Check Exist
     * @param array $aCondition
     * @return bool
     */
    public function isExist($aCondition) {
        $iCount = $this->database()
            ->select('count(*)')
            ->from($this->_sTable)
            ->where($this->getCondition($aCondition))
            ->execute('getField');
        if ($iCount > 0) {
            return true;
        }
        else {
            return false;
        }
    }

    /**
     * get group name from user
     * @param int $iUserId
     * @return string
     */
    public function getLabel($iUserId) {
        $aUser = $this->database()
            ->select('u.user_group_id as group_id, g.title as group_name')
            ->from($this->_sTableUser, 'u')
            ->leftJoin($this->_sTableParent, 'g', 'u.user_group_id = g.user_group_id')
            ->where ('user_id = '. $iUserId)
            ->execute('getRow');
        $aLabel = $this->database()
            ->select('l.name as name')
            ->from($this->_sTable, 'l')
            ->where('group_id ='. $aUser['group_id'])
            ->execute('getField');

        if ($aLabel != "") {
            return $aLabel;
        }
        else {
            if ($aUser['group_id'] == 2) {
                return "";
            }
            else {
                return $aUser['group_name'];
            }

        }
    }

    /**
     * changeLabel for one user
     * @param $iUserId
     * @return bool
     */
    public function changeLabel($iUserId) {
        $iPoint = Phpfox::getService('answer.point')->getPoint($iUserId);
        $iGroupId = $this->database()
            ->select('user_group_id')
            ->from($this->_sTableUser)
            ->where('user_id = '.$iUserId)
            ->execute('getField');
        $aLevel = $this->database()
            ->select('group_id, previous_group, minpoint, maxpoint')
            ->from($this->_sTable)
            ->where ('minpoint <= '. $iPoint .' and maxpoint >= '. $iPoint)
            ->execute('getRow');

        if (($iGroupId != $aLevel['group_id']) && ($iGroupId == $aLevel['previous_group']) ) {
            $Val['user_group_id'] = $aLevel['group_id'];
            $this->database()->update($this->_sTableUser, $Val, 'user_id = '. $iUserId);
        }
        if (($iGroupId == $aLevel['group_id']) && ($iGroupId != $aLevel['previous_group']) && ($iPoint < $aLevel['minpoint'])) {
            $Val['user_group_id'] = $aLevel['previous_group'];
            $this->database()->update($this->_sTableUser, $Val, 'user_id = '. $iUserId);
        }
        return true;
    }
    /**
     * gel info all levels
     * @return array
     */
    public function getAllInfo() {
        $aRecords = $this->database()
            ->select('l.minpoint, l.maxpoint, g.title as group_name, l.name as label')
            ->from($this->_sTable, 'l')
            ->leftJoin($this->_sTableParent, 'g', 'l.group_id = g.user_group_id')
            ->order('l.minpoint')
            ->execute('getRows');
        return $aRecords;
    }

    /**
     * get user info like : point, label ....
     * @param int $iUserId
     * @return array
     */
    public function getUserInfo( $iUserId ) {
        $aUser = $this->database()
            ->select('u.user_name, u.full_name, u.user_image, u.user_group_id')
            ->from($this->_sTableUser, 'u')
            ->leftJoin($this->_sTableParent, 'g', 'u.user_group_id = g.user_group_id' )
            ->where('u.user_id = '. $iUserId)
            ->execute('getRow');
        $aUser['label'] = $this->getLabel($iUserId);
        $aUser['point'] = Phpfox::getService('answer.point')->getPoint($iUserId);
        $iMaxpoint = $this->database()
            ->select('maxpoint')
            ->from($this->_sTable)
            ->where('group_id = '. $aUser['user_group_id'])
            ->execute('getField');
        if ($iMaxpoint > 0) {
            $aUser['maxpoint'] = $iMaxpoint;
        }
        else {
            $aUser['maxpoint'] = 0;
        }
        return $aUser;
    }
}